# coding=utf-8
from math import sqrt

import pickle
import face_recognition
import os
import requests
import time
from face_recognition import face_locations
from sklearn import neighbors

from worldcup.apps.userModel.models import Player
from worldcup.commons.CommonResult import rest, CommonResult


@rest
def predict(request):
	openid = request.GET.get("openid")
	if openid is None:
		return CommonResult(-1, "openid为空")
	img_path = "/home/gmj/code/img/" + openid + ".jpg"

	img = face_recognition.load_image_file(img_path)
	faces_loc = face_locations(img)
	if len(faces_loc) == 0:
		return CommonResult(-1, "没找到脸～～")
	faces_encodings = face_recognition.face_encodings(img, known_face_locations=faces_loc)

	with open("/home/gmj/code/knn_clf", 'rb') as f:
		knn_clf = pickle.load(f)

	closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
	is_recognized = [closest_distances[0][i][0] <= .5 for i in range(len(faces_loc))]
	for pred, loc, rec in zip(knn_clf.predict(faces_encodings), faces_loc, is_recognized):
		if rec:
			id = pred
			player = Player.objects.values("name", "img_url").filter(id=id).get()
			return CommonResult(0, {
				"name": player["name"],
				"imgUrl": player["img_url"],
			})
	return CommonResult("-1", "没有匹配")

@rest
def train(request):
	pre = time.time()
	X = []
	y = []
	while True:
		players = Player.objects.all()
		if len(players) == 0:
			break
		for player in players:
			if player.ext1 is not None and player.ext1 != "":
				continue
			img_url = player.img_url
			suffix = os.path.splitext(img_url)[1]
			response = requests.get(img_url)
			with open('/home/gmj/code/img/player/' + str(player.id) + suffix, 'wb') as f:
				f.write(response.content)
				f.close()
			try:
				image = face_recognition.load_image_file('/home/gmj/code/img/player/' + str(player.id) + suffix)
			except IOError:
				continue
			faces_bboxes = face_locations(image)
			if len(faces_bboxes) != 1:
				continue
			X.append(face_recognition.face_encodings(image, known_face_locations=faces_bboxes)[0])
			y.append(player.id)
		break
	n_neighbors = int(round(sqrt(len(X))))
	knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm='ball_tree', weights='distance')
	knn_clf.fit(X, y)

	with open("/home/gmj/code/knn_clf", 'wb') as f:
		pickle.dump(knn_clf, f)
	return CommonResult(0, time.time() - pre)

